package com.duo.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.duo.dto.GoodsSalesDTO;
import com.duo.entity.Orders;
import com.duo.entity.User;
import com.duo.mapper.OrderMapper;
import com.duo.mapper.UserMapper;
import com.duo.service.ReportService;
import com.duo.vo.BusinessDataVO;
import com.duo.vo.SalesTop10ReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    public BigDecimal getTurnoverStatistics(LocalDate begin, LocalDate end) {
        BigDecimal res = BigDecimal.ZERO;
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Orders::getAmount)
                .between(Orders::getOrderTime, begin, end)
                .eq(Orders::getStatus, 3);

        List<Object> sumAmountList = orderMapper.selectObjs(queryWrapper);
        for (Object obj : sumAmountList) {
            if (obj instanceof BigDecimal) {
                res = res.add((BigDecimal) obj);
            }
        }
        // 返回结果
        return res;
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    public Long getUserStatistics(LocalDate begin, LocalDate end) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(User::getCreateTime, begin, end);
        return userMapper.selectCount(queryWrapper);

    }

    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    public Long getOrderStatistics(LocalDate begin, LocalDate end) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(Orders::getOrderTime, begin, end);
        queryWrapper.eq(Orders::getStatus, 3);
        return orderMapper.selectCount(queryWrapper);
    }


    /**
     * 统计指定时间区间内的销量排名前10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StrUtil.join(",", names);

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StrUtil.join(",", numbers);

        //封装返回结果数据
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(LocalDate dateBegin, LocalDate dateEnd, HttpServletResponse response) {
        //1. 查询数据库，获取营业数据
        BusinessDataVO businessDataVO = getBusinessData(dateBegin, dateEnd);

        //2. 通过POI将数据写入到Excel文件中
        String fileName = String.format("template/运营数据报表模板-%s-%s.xlsx", dateBegin, dateEnd);
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover().doubleValue());
            row.getCell(4).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < (dateEnd.until(dateBegin, ChronoUnit.DAYS)); i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = getBusinessData(date, date.plusDays(1));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover().doubleValue());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getUnitPrice());
                row.getCell(5).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private BusinessDataVO getBusinessData(LocalDate dateBegin, LocalDate dateEnd) {

        BigDecimal turnover = this.getTurnoverStatistics(dateBegin, dateEnd);
        Long validOrderCount = this.getOrderStatistics(dateBegin, dateEnd);
        Long newUsers = this.getUserStatistics(dateBegin, dateEnd);
        double unitPrice = 0.0;
        if (validOrderCount != 0) {
            unitPrice = turnover.doubleValue() / validOrderCount;
        }
        //查询概览数据
        return new BusinessDataVO(turnover, validOrderCount, unitPrice, newUsers);


    }
}
